package com.lnold.redis.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class ConfigService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final String CONFIG_HASH_KEY = "config";


    public void setConfigValue(String name, String value) {
        redisTemplate.opsForHash().put(CONFIG_HASH_KEY, name, value);
    }

    public String getConfigValue(String name) {
        return (String) redisTemplate.opsForHash().get(CONFIG_HASH_KEY, name);
    }

    public void deleteConfigValue(String name) {
        redisTemplate.opsForHash().delete(CONFIG_HASH_KEY, name);
    }

    public Map<String, String> getAllConfigs() {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(CONFIG_HASH_KEY);
        Map<String, String> configs = new HashMap<>();
        entries.forEach((key, value) -> configs.put((String) key, (String) value));
        return configs;
    }

    public void publishUpdate(String name) {
        redisTemplate.convertAndSend("configUpdates", name+"="+getConfigValue(name));
    }

    public void importConfig(File configFile) {
        try (FileReader fileReader = new FileReader(configFile)) {
            Map<String, String> configMap = new ObjectMapper().readValue(fileReader, HashMap.class);
            configMap.forEach(this::setConfigValue);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void exportConfig(File configFile) {
        Map<String, String> configMap = getAllConfigs();

        try (FileWriter fileWriter = new FileWriter(configFile)) {
            new ObjectMapper().writeValue(fileWriter, configMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}